package com.aidong.device.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

import com.aidong.device.controllers.concerns.Success;
import com.aidong.device.entity.*;
import com.aidong.device.util.ExUtil;
import com.aidong.device.util.PrintItem;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aidong.device.dao.ExCodeDao;
import com.aidong.device.dao.ExLogDao;
import org.springframework.ui.ModelMap;

@Service
public class ExCodeServiceImpl implements com.aidong.device.service.ExCodeService {
    @Autowired
    ExLogDao exLogDao;
    @Autowired
    ExCodeDao exCodeDao;

    @Override
    public List<Integer> getExGoodList(String machineId, String code) {
        List<ExGood> goodList = exCodeDao.getExGoodList(machineId, code);
        List<ExLog> exchangedList = exLogDao.getExLogList(code, ExUtil.N_LOG);
        for (ExGood exGood : goodList) {
            int exchangedAmount = 0;
            for (ExLog exLog : exchangedList) {
                if (exLog.getGoodId() == exGood.getGoodId()) {
                    exchangedAmount += exLog.getAmount();
                }
            }
            exGood.setAmount(exGood.getAmount() - exchangedAmount);
        }
        List<Integer> skuList = new ArrayList<Integer>();
        for (ExGood exGood : goodList) {
            if (exGood.getAmount() > 0) {
                for (int i = 0; i < exGood.getAmount(); i++) {
                    skuList.add(exGood.getGoodId());
                }
            }
        }
        return skuList;
    }

    @Override
    public void addExLog(List<ExLog> logList) {
        exLogDao.addExLog(logList);
    }

    @Override
    public void addExLog(ExLog exLog, String machineId) {
        if (exLog.getType() == 0) {
            Integer storeId = exCodeDao.getStoreId(machineId);
            if (storeId != null)
                checkIn(exLog.getCode(), storeId);
        } else {
            exCodeDao.checkIn(exLog.getCode());
        }
        List<ExLog> exLogs = new ArrayList<>();
        exLogs.add(exLog);
        exLogDao.addExLog(exLogs);
    }

    @Override
    public Success getAppointment(String deviceId, String code, int lessonType) {
        Success success = new Success();
        List<ExPrintItem> printItems = new ArrayList<>();
        List<ExLog> exLogs = exLogDao.getExLogList(code, lessonType);
        if (exLogs.size() >= 3) {
            return success;
        } else {
            Map<String, String> appointment;
            if (lessonType == 1) {
                appointment = exCodeDao.getAppointment(deviceId, code);
            } else {
                Integer storeId = exCodeDao.getStoreId(deviceId);
                if (storeId == null) {
                    appointment = null;
                } else {
                    appointment = getAppointment(code, storeId);
                }
            }
            if (appointment == null) {
                return success;
            } else {
                for (PrintItem item : PrintItem.values()) {
                    if (appointment.containsKey(item.getColumn())) {
                        printItems.add(new ExPrintItem(item.getName(), appointment.get(item.getColumn())));
                    } else {
                        printItems.add(new ExPrintItem(item.getName(), "无"));
                    }
                }
                printItems.add(new ExPrintItem("验证码", code));
                ModelMap map = new ModelMap();
                map.addAttribute("lessonType", lessonType);
                map.addAttribute("code", code);
                map.addAttribute("isPrint", exLogs.size() > 0 ? 1 : 0);
                map.addAttribute("lessonInfo", new ExPrintInfo(ExUtil.PRINTTITLE, printItems));
                success.setData(map);
            }
        }
        return success;
    }

    private Map<String, String> getAppointment(String code, int storeId) {
        try {
            URL url = new URL("http://open.aidong.me/checkin/" + code + "?store=" + storeId);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String tmp = "";
            String jsonStr = "";
            while ((tmp = in.readLine()) != null) {
                jsonStr += tmp;
            }
            JSONObject object = new JSONObject(jsonStr);
            JSONObject dataObj = object.getJSONObject("data");
            Map<String, String> result = new HashMap<>();
            result.put(PrintItem.course.getColumn(), dataObj.getString("course"));
            result.put(PrintItem.store.getColumn(), dataObj.getString("store"));
            result.put(PrintItem.classroom.getColumn(), dataObj.getString("classroom"));
            result.put(PrintItem.classTime.getColumn(), dataObj.getString("class_time"));
            result.put(PrintItem.printTime.getColumn(), dataObj.getString("checkin_time"));
            result.put(PrintItem.userName.getColumn(), dataObj.getString("member"));
            result.put(PrintItem.seat.getColumn(), dataObj.getString("seat"));
            in.close();
            urlConnection.disconnect();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private boolean checkIn(String code, int storeId) {
        try {
            URL url = new URL("http://open.aidong.me/checkin/" + code + "?store=" + storeId);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
            int respCode = urlConnection.getResponseCode();
            if (respCode == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
